import { create } from 'zustand';
import API from '@/http';
import { message } from 'antd';
const AUTH_KEY = '__AUTH';

interface UserInfo {
  id: number;
  aff: number;
  username: string;
  token: string;
}

const NONE_USER_INFO: UserInfo = {
  id: -1,
  aff: -1,
  username: '',
  token: '',
};

interface AuthState {
  userInfo: UserInfo;
  isAuthenticated: () => boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set, get) => ({
  userInfo:
    JSON.parse(localStorage.getItem(AUTH_KEY) || '""') || NONE_USER_INFO,

  isAuthenticated: () => get().userInfo?.token !== '',

  login: async (username, password) => {
    try {
      const userInfo = await API.Auth.login({ data: { username, password } });
      localStorage.setItem(AUTH_KEY, JSON.stringify(userInfo));
      set({ userInfo });
    } catch (e) {
      message.error(`${e}`);
      console.error(e);
    }
  },

  logout: () => {
    return new Promise((resolve) => {
      localStorage.removeItem(AUTH_KEY);
      set({ userInfo: NONE_USER_INFO });
      resolve();
    });
  },
}));
